# -*- coding: utf-8 -*-

import os
from com.maycur import config_loader
from com.maycur.git.base.ops_operation import OpsOperation
from conf.entity.module.git_config import GitConfig


class OpsBatchOperation:

    git_config: GitConfig
    ops_operation: OpsOperation

    def __init__(self):
        # 获取配置
        self.git_config = config_loader.get_git_config()
        self.ops_operation = OpsOperation(self.git_config.ops_config)

    def make_ops_request_by_file(self, file_path: str):
        if not self.ops_operation.ops_config.do_make_request:
            print(f'ops make request switch is off, do nothing')
            return

        # 确定待提交ops申请的服务
        ops_candidate_service = set()
        file_path = os.path.join(os.getcwd(), file_path)
        with open(file_path) as f:
            for line in f.readlines():
                # 去掉换行符
                ops_candidate_service.add(line.replace('\n', ''))

        for branch_pair in self.git_config.branch_pairs:
            print(f'\nstart processing branch pair: {branch_pair.pair_name} ...')
            print('========================================================================')

            for project in branch_pair.projects:
                # 不处理不在ops_candidate_service.txt中的微服务
                if project.name not in ops_candidate_service:
                    continue
                print(f'start processing project: [{project.name}] ...')
                self.ops_operation.create_deployment_request_if_need(branch_pair, project)


if __name__ == '__main__':
    ops_batch_operation = OpsBatchOperation()
    ops_batch_operation.make_ops_request_by_file('ops/ops_candidate_service.txt')
